package Send2ME::Web;
use Dancer ':syntax';

use Send2ME::Loginza;
use Send2ME::Register;
use Send2ME::Personal;
use Send2ME::RulePage;
use Send2ME::Update::Personal;
use Send2ME::Create::Rule;
use Send2ME::Delete::Rule;
use Send2ME::Dao::Auth;
use Send2ME::Dao::User;
use Send2ME::Magic::Magic;
use Digest::Perl::MD5 'md5_hex';

our $VERSION = '0.1';

prefix undef;

sub language {
  my $tokens = shift;
  
  my $language = locale(request->header('Accept-Language'), qw(en ru));

  $language = 'ru' if (request->host =~ /ru\./i);
  $language = 'en' if (request->host =~ /en\./i);
  
  $tokens->{language} = $language;
}

hook before_template_render => sub {
	language(shift);
};

hook before_layout_render => sub {
	language(shift);
};

post '/' => sub {
	my ($login, $password) = (params->{login}, params->{password});
	
	if (!$login || !$password ||
		length($login) < 3 || length($password) < 3 ||
		!isAcceptable($login) || !isAcceptable($password)) {
		return template 'login_failed';
	}
	
	my $user = getUser({ recipient => $login });
	
	return template 'login_failed' if (!$user);
	return template 'login_failed' if ($user->{password} ne md5_hex($password));
	
	currentUser($user);
	redirect '/personal'
};

get '/' => sub {
	if (credential->{logged_in}) {
		if (!credential->{user}->{recipient}) {
			redirect '/update/personal';
		} else {
			redirect '/personal';
		}
	} else { 
		template 'index', { credential => credential };
	}
};

get '/error/:error' => sub {
	template 'error', { id => params->{error} };
};

get '/logout' => sub {
	logout();
	redirect '/';	
};

1;